﻿using NCD.Common.Helpers;
using System.Collections.Concurrent;
using System.Net.WebSockets;
using WebSocketApi.Common;
using WebSocketApi.Interface;

namespace WebSocketApi.Services
{
    /// <summary>
    /// Socket连接对象管理
    /// </summary>
    public class SocketDataManager:ISocketDataManager
    {
        private static readonly ConcurrentDictionary<string, WebSocket> Connections = new ConcurrentDictionary<string, WebSocket>();

        public SocketDataManager()
        {
        }

        /// <summary>
        /// 获取所有Socket连接
        /// </summary>
        /// <returns></returns>
        public ConcurrentDictionary<string, WebSocket> GetAllConnections()
        {
            return Connections;
        }

        /// <summary>
        /// 根据Id获取指定Socket连接
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public WebSocket GetSocketById(string id)
        {
            var list = Connections;
            return Connections.FirstOrDefault(x => x.Key == id).Value;
        }

        /// <summary>
        /// 获取Socket连接ID
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public string GetSocketId(WebSocket socket)
        {
            return Connections.FirstOrDefault(x => x.Value == socket).Key;
        }

        /// <summary>
        /// 连接账号获取SocketId
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public string GetSocketId(string account)
        {
            var cacheKey = $"{IdGenerate.GenerateMd5ByRequest(account)}_verify";
            return cacheKey;
        }

        /// <summary>
        /// 删除指定ID的Socket，并关闭该连接
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task RemoveSocketAsync(string id)
        {
            Connections.TryRemove(id, out var socket);
            if (socket != null && socket?.State == WebSocketState.Open)
            {
                Console.WriteLine("socket连接关闭");
                await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "socket连接关闭", CancellationToken.None);
            }
        }

        /// <summary>
        /// 添加新的Socket
        /// </summary>
        /// <param name="socketId"></param>
        /// <param name="socket"></param>
        public async Task<bool> AddSocket(string socketId, WebSocket socket)
        {
            var result = Connections.TryAdd(socketId, socket);
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 变更Socket令牌
        /// </summary>
        /// <param name="oldSocketKey"></param>
        /// <param name="newSocketKey"></param>
        /// <returns></returns>
        public async Task<bool> EditSocketKey(string oldSocketKey, string newSocketKey)
        {
            var result = false;
            if (Connections.Any(it => it.Key == oldSocketKey))
            {
                //清除旧的连接
                Connections.TryRemove(oldSocketKey, out var socket1);
                result = Connections.TryAdd(newSocketKey, socket1);
            }
            if (Connections.Any(it => it.Key == newSocketKey))
            {
                //重新确定、清除已建立令牌的旧的连接
                Console.WriteLine($"oldSocketKey:{oldSocketKey}, newSocketKey:{newSocketKey}");
                var removeResult = Connections.TryRemove(oldSocketKey, out var socket2);
                Connections.TryAdd(newSocketKey, socket2);
            }

            result = Connections.Any(it => it.Key == newSocketKey);
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 总连接数
        /// </summary>
        /// <returns></returns>
        public int GetCount()
        {
            return Connections.Count;
        }

    }
}
